package com.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.logging.Logger;

@Controller
public class UserController {

  private static final Logger log = Logger.getLogger(UserController.class.toString());

  @RequestMapping("/")
  public String index() {
    return "login";
  }

  @RequestMapping("/login")
  public String login(String username, String password, Model model) {
    //创建一个shiro的Subject对象，利用这个对象来完成用户的登录认证
    Subject subject = SecurityUtils.getSubject();

    //判断当前用户是否已经认证过，如果已经认证过着不需要认证;如果没有认证过则完成认证
    if (!subject.isAuthenticated()) {
      //创建一个用户账号和密码的Token对象，并设置用户输入的账号和密码
      //这个对象将在Shiro中被获取
      UsernamePasswordToken token = new UsernamePasswordToken(username, password);
      try {
        //如账号不存在或密码错误等等，需要根据不同的异常类型来判断用户的登录状态，并给予友好的信息提示
        //调用login后，Shiro就会自动执行自定义的Realm中的认证方法
        subject.login(token);

      } catch (UnknownAccountException e) {
        //表示用户的账号错误，这个异常是在后台抛出
        log.info("---------------账号不存在");
        model.addAttribute("errorMessage", "账号不存在");
        return "login";
      } catch (LockedAccountException e) {
        //表示用户的账号被锁定，这个异常是在后台抛出
        log.info("===============账号被锁定");
        model.addAttribute("errorMessage", "账号被冻结");
        return "login";
      } catch (IncorrectCredentialsException e) {
        //表示用户的密码错误，这个异常是shiro在认证密码时抛出
        log.info("***************密码不匹配");
        model.addAttribute("errorMessage", "密码错误");
        return "login";
      }
    }
    return "redirect:/success";
  }

  @RequestMapping("/success")
  public String success() {
    return "success";
  }

  @RequestMapping("/noPermission")
  public String noPermission() {
    return "noPermission";
  }

  @RequiresRoles({"admin", "user"})
  @RequestMapping("/user/test")
  public @ResponseBody String userTest() {
    return "这是userTest请求";
  }

  @RequiresRoles("admin")
  @RequestMapping("/admin/test")
  public @ResponseBody String adminTest() {
    return "这是adminTest请求";
  }

  @RequestMapping("/admin/add")
  public @ResponseBody String adminAdd() {
    Subject subject = SecurityUtils.getSubject();
    return "这是adminAdd请求";
  }
}
